<?php
class CmsAccess {
	/**
	 * Static varible containing class itself
	 *
	 * @var self
	 */
	protected static $_instance = null;
	
	
	/**
	 * Returns current admin
	 *
	 * @var SingleAdministrator
	 */
	private static $_admin = null;
	
 	/**
 	 * Returning the instance of CmsAuth object. Classic singltone patern
 	 *
 	 * @return SingleAdministrator
 	 */
 	public static function getInstance()
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }
    
    
    /**
	 * Returns current admin
	 *
	 * @return SingleAdministrator
	 */
    public static function getAdmin() {
    	
    	CmsAuth::check();
    	if (self::$_admin===null) {
	    	$adminSession = new Zend_Session_Namespace('Cms_Admin');
			self::$_admin = MF_Main::getInstance()->Administrator->getById($adminSession->id);
    	}
    	return self::$_admin;
    }
    
    
    public static function checkMenu($menu) {
    	
    	// TODO введено для дебага, потом убрать
    	//return TRUE;
    	//
    	
    	if (self::getAdmin()->checkMenu($menu)) {
    		return true;
    	}
    	$admin_groups = self::getAdmin()->groupList();
    	for ($g=0;$g<$admin_groups->length();$g++) {
    		if ($admin_groups->item($g)->checkMenu($menu)) {
    			return true;
    		}
    	}
    	return false;
    }
    
    public static function restrictMenu($menu) {
    	if (!self::checkMenu($menu)) {
    		throw new Zend_Controller_Action_Exception("You don't have permission to manage this module",404);
    	}
    }
    
    
    public static function checkModule($modul) {
    	// TODO введено для дебага, потом убрать
    	//return TRUE;
    	//
    	
    	if (self::getAdmin()->checkModule($modul)) {
    		return true;
    	}
    	$admin_groups = self::getAdmin()->groupList();
    	for ($g=0;$g<$admin_groups->length();$g++) {
    		if ($admin_groups->item($g)->checkModule($modul)) {
    			return true;
    		}
    	}
    	return false;
    }
    
    public static function restrictModule($module) {
    	if (!self::checkModule($module)) {
    		throw new Zend_Controller_Action_Exception("You don't have permission to manage this module",404);
    	}
    }
    
}